package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;

import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class ApiServiceImpl implements ApiService {

    //stringRedisTemplate与Redistemplate有啥区别
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdChannelFeign adChannelFeign;

    /**
     * 查询频道列表
     *
     * @return
     */

    @Override
    public List<AdChannel> getChannelList() {
        List<AdChannel> list = new ArrayList<>();

        //1. 先从redis查询
        // opsForValue 使用 key 查询字符串类型的操作
        String jsonString = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);

        //2. 如果redis没数据
        if (StringUtils.isEmpty(jsonString)){
            //3. 远程调用admin微服务，查询所有频道
            ResultVo<List<AdChannel>> resultVo = adChannelFeign.findAll();
            if (!resultVo.isSuccess()){
                throw new LeadNewsException("远程调用查询频道失败!");
            }
            list = resultVo.getData();

            //4. 存入redis
            // 转成json的字符串
            jsonString = JSON.toJSONString(list);

            //存入redis
            stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,jsonString);
        }else {
            //有值
            list = JSON.parseArray(jsonString,AdChannel.class);
        }

        //5. 返回
        return list;
    }
}
